package com.zhz.leetcode.utils;

import com.zhz.leetcode.entity.ListNode;

import java.util.ArrayList;

public class LinkedListUtils {

    /**
     * 打印链表
     */
    public static void printList(ListNode head) {
        ListNode tmp = head;
        StringBuilder sb = new StringBuilder();
        while (true) {
            if (tmp == null) {
                sb.append("链表无数据");
                break;
            }
            sb.append(tmp.val).append(" ");
            if (tmp.next != null) {
                tmp = tmp.next;
            } else {
                break;
            }
        }
        System.out.println(sb);
    }

    /**
     * 根据list创建链表
     */
    public static ListNode createListNode(ArrayList<Integer> list) {
        ListNode head = new ListNode(0);
        ListNode prev = head;
        for (Integer integer : list) {
            prev.next = new ListNode(integer);
            prev = prev.next;
        }
        return head.next;
    }


    /**
     * 根据list创建链表
     */
    public static ListNode createListNode(int[] nums) {
        ListNode head = new ListNode(0);
        ListNode prev = head;
        for (int num : nums) {
            prev.next = new ListNode(num);
            prev = prev.next;
        }
        return head.next;
    }

}
